import 'dart:isolate';

class IsolateDemo {
  Isolate? isolate;
  ReceivePort receivePort = ReceivePort(); // 用于接收消息的端口

  // 开启异步耗时任务
  void startNewIsolate() async {
    Isolate.spawn(dataProcessingIsolate, receivePort.sendPort).then((value) {
      isolate = value;
    });

    receivePort.listen((data) {
      print('Received data: $data');
    });
  }

  //关闭 Isolate：当你完成了 Isolate 的任务后，应该关闭它以释放资源。
  finish() {
    receivePort.close();
    isolate?.kill(priority: Isolate.immediate);
  }

  // 耗时操作
  void dataProcessingIsolate(SendPort sendPort) {
    String data = 'Processed data';
    sendPort.send(data); // 发送数据回主线程
  }
}
